﻿//-----------------------------------------------
// <copyright file="ImageConverter.cs" company="FER">
//     Copyright (c) All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace NMBP.Models.Converters
{
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Windows.Media.Imaging;

    /// <summary>
    /// Static class converts image converter
    /// </summary>
    public static class MyImageConverter
    {
        /// <summary>
        /// Convertes image to byte array
        /// </summary>
        /// <param name="imageIn">Image to be converted</param>
        /// <returns>Byte array from image</returns>
        public static byte[] ImageToByteArray(Image imageIn)
        {
            var ms = new MemoryStream();
            imageIn.Save(ms, ImageFormat.Png);

            return ms.ToArray();
        }

        /// <summary>
        /// Converts Byte array to image
        /// </summary>
        /// <param name="byteArrayIn">byte array to be converted</param>
        /// <returns>Converted image</returns>
        public static Image ByteArrayToImage(byte[] byteArrayIn)
        {
            var ms = new MemoryStream(byteArrayIn);
            var returnImage = Image.FromStream(ms);

            return returnImage;
        }

        /// <summary>
        /// Converts to bitmap image from byte array
        /// </summary>
        /// <param name="bitmap">array of bytes representig bitmap</param>
        /// <returns>BitmapImage to display in wpf container Image</returns>
        public static BitmapImage ConvertToBitmapImage(byte[] bitmap)
        {
            var systemBitmap = ByteArrayToImage(bitmap);
            MemoryStream ms = new MemoryStream();
            systemBitmap.Save(ms, ImageFormat.Png);
            ms.Position = 0;

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = ms;
            bi.EndInit();

            return bi;
        }
    }
}
